<template>
  <div>
    <el-card>
      <el-row :gutter="10">
        <!--用户搜索-->
        <el-col :span="5">
          <el-input placeholder="请输入用户名" v-model="userListReqForm.userName">
            <el-button slot="append" icon="el-icon-search" @click="SearchBtnClick"></el-button>
          </el-input>
        </el-col>
        <!--工号搜索-->
        <el-col :span="5">
          <el-input placeholder="请输入工号" v-model="userListReqForm.userCardId">
            <el-button slot="append" icon="el-icon-search" @click="SearchBtnClick"></el-button>
          </el-input>
        </el-col>
        <!-- 状态搜索-->
        <el-col :span="8">
          <el-row>
            <el-col :span="12">
              <el-select v-model="statusSelect" placeholder="请选择" style="float:right;">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-button icon="el-icon-search" style="background-color: #f5f7fa; float:left;" @click="SearchBtnClick"></el-button>
            </el-col>
          </el-row>
        </el-col>
        <!--添加用户-->
        <el-col :span="6" style="text-align: right;">
          <el-button type="primary" size="mini" @click="addUserClick">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表-->
      <el-table :data="userList" border>
        <el-table-column label="No" type="index"></el-table-column>
        <el-table-column label="用户名" prop="userName" min-width="200"></el-table-column>
        <el-table-column label="用户角色" prop="roleName" min-width="200"></el-table-column>
        <el-table-column label="用户工号" prop="userCardId" min-width="200"></el-table-column>
        <el-table-column label="状态" width="150">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.userStatus" @change="userStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="userEditClick(scope.row)">编辑</el-button>
            <el-button type="success" size="mini" @click="roleClick(scope.row)">角色</el-button>
            <el-button type="primary" size="mini" @click="menuClick(scope.row)">菜单</el-button>
            <el-button type="warning" size="mini" @click="powerClick(scope.row)">权限</el-button>
            <el-button type="danger" size="mini" @click="deleteClick(scope.row.userId, scope.row.userName)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="userListReqForm.pageNum"
        :page-sizes="[10, 20, 30, 40]" :page-size="userListReqForm.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--添加用户窗口-->
    <el-dialog v-dialogDrag title="添加用户" :visible.sync="addUserDialog" width="40%" @opened="addUserDialogOpened"
      :close-on-click-modal="false" center>
      <span style="text-align: center">
        <el-form ref="userRegisterFormRef" :model="userRegisterForm" :rules="userRegisterFormRules" label-position="right"
          label-width="70px">
          <!--用户名-->
          <el-form-item label="用户名" prop="userName" v-on:keyup.enter.native="register">
            <el-input ref="userNameInputRef" v-model="userRegisterForm.userName"></el-input>
          </el-form-item>
          <!--密码-->
          <el-form-item label="密码" prop="userPassword" v-on:keyup.enter.native="register">
            <el-input v-model="userRegisterForm.userPassword" type="password"></el-input>
          </el-form-item>
          <!--工号-->
          <el-form-item label="工号" prop="userCardId" v-on:keyup.enter.native="register">
            <el-input v-model="userRegisterForm.userCardId" type="password"></el-input>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="register">添加</el-button>
          <el-button type="info" @click="resetRegisterForm">重置</el-button>
        </div>
      </span>
    </el-dialog>
    <el-dialog v-dialogDrag title="用户角色" :visible.sync="userRoleDialog" width="25%" center :close-on-click-modal="false">
      <span style="text-align: center">
        <div>
          <el-select v-model="roleSelect" placeholder="请选择">
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleName">
            </el-option>
          </el-select>
        </div>
        <div style="margin-top: 25px;">
          <el-button type="primary" @click="editUserRole">提交</el-button>
        </div>
      </span>
    </el-dialog>
    <el-dialog v-dialogDrag title="菜单权限" :visible.sync="menuPowerDialog" width="40%" center :close-on-click-modal="false">
      <span style="text-align: center">
        <el-tree :data="userMenuList" show-checkbox node-key="menuRoot" ref="userMenuListTreeRef" highlight-current
          :props="userMenuListTreeProps">
        </el-tree>
        <div>
          <el-button type="primary" @click="editUserPower">提交</el-button>
        </div>
      </span>
    </el-dialog>
    <el-dialog v-dialogDrag title="用户权限" :visible.sync="userPowerDialog" width="90%" center :close-on-click-modal="false">
      <span style="text-align: center">
        <el-table :data="userPowerList" border>
          <el-table-column label="No" type="index"></el-table-column>
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table :data="props.row.userPowerVOS" border :header-cell-style="{background:'#b6d5f5',color:'#606266'}">
                <el-table-column label="权限名称" prop="powerName" min-width="200"></el-table-column>
                <el-table-column label="权限路径" prop="powerPath" min-width="200"></el-table-column>
                <el-table-column label="状态" width="150">
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.isEnable" @change="userPowerStatusChange(scope.row)"></el-switch>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column header-align="center" label="权限分组" prop="powerGroup" min-width="200" align="left"></el-table-column>
        </el-table>
      </span>
    </el-dialog>
    <el-dialog v-dialogDrag title="编辑用户" :visible.sync="editUserDialog" width="40%" @closed="editUserDialogClosed"
      center :close-on-click-modal="false">
      <span style="text-align: center">
        <el-form ref="userEditFormRef" :model="userEditForm" :rules="userEditFormRules" label-position="right"
          label-width="80px">
          <el-form-item label="用户工号:" prop="userCardId" v-on:keyup.enter.native="editUser">
            <el-input v-model="userEditForm.userCardId"></el-input>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="editUser">提交</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'user',
    data() {
      return {
        userId: -1,
        userRoleDialog: false,
        editUserDialog: false,
        roleSelect: '',
        menuPowerDialog: false,
        userMenuList: [],
        userMenuListTreeProps: {
          children: 'children',
          label: 'menuName'
        },
        userPowerDialog: false,
        userPowerList: [],
        userListReqForm: {
          pageNum: 1,
          pageSize: 10,
          userName: '',
          userCardId: ''
        },
        userRegisterForm: {
          userName: '',
          userPassword: '',
          userCardId: ''
        },
        userEditForm: {
          userId: -1,
          userCardId: ''
        },
        userEditFormRules: {},
        userRegisterFormRules: {
          userName: [{
              required: true,
              message: '请输入用户名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 10,
              message: '长度在 2 到 10 个字符',
              trigger: 'blur'
            }
          ],
          userPassword: [{
              required: true,
              message: '请输入用户密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 10,
              message: '长度在 6 到 10 个字符',
              trigger: 'blur'
            }
          ]
        },
        userList: [],
        total: 0,
        addUserDialog: false,
        labelPosition: 'left',
        statusSelect: 'all',
        statusOptions: [{
            value: 'all',
            label: '全部'
          },
          {
            value: 'true',
            label: '开启'
          },
          {
            value: 'false',
            label: '冻结'
          }
        ],
        roleOptions: []
      }
    },
    methods: {
      async getUserList() {
        if (this.statusSelect === 'true') {
          this.userListReqForm.userStatus = true
        } else if (this.statusSelect === 'false') {
          this.userListReqForm.userStatus = false
        } else if (this.statusSelect === 'all') {
          delete (this.userListReqForm.userStatus)
        }
        const res = await this.$apiUtil.postByJson('user/list', this.userListReqForm)
        console.log(res)
        if (res.code !== '200') {
          return this.$message.error(res.msg)
        }
        this.userList = res.data.userVOS
        this.total = res.data.totalSize
      },
      SearchBtnClick() {
        this.getUserList()
      },
      handleSizeChange(newSize) {
        this.userListReqForm.pageSize = newSize
        this.getUserList()
      },
      handleCurrentChange(newPage) {
        this.userListReqForm.pageNum = newPage
        this.getUserList()
      },
      register() {
        this.$refs.userRegisterFormRef.validate(async valid => {
          if (!valid) return
          const res = await this.$apiUtil.postByJson('user/register', this.userRegisterForm)
          console.log(res)
          if (res.code !== '200') {
            return this.$message.error(res.msg)
          }
          this.$message.success('添加用户成功')
          this.getUserList()
          this.addUserDialog = false
        })
      },
      resetRegisterForm() {
        this.$refs.userRegisterFormRef.resetFields()
      },
      addUserClick() {
        this.addUserDialog = true
      },
      addUserDialogOpened() {
        if (this.$refs.userRegisterFormRef !== undefined) {
          this.$refs.userRegisterFormRef.resetFields()
        }
        this.$refs.userNameInputRef.focus()
      },
      async userStatusChange(row) {
        const res = await this.$apiUtil.postByForm('user/changeStatus', {
          userId: row.userId
        })
        console.log(res)
        if (res.code !== '200') {
          row.userStatus = !row.userStatus
          return this.$message.error(res.msg)
        }
        this.$message.success('修改用户状态成功')
        this.getUserList()
      },
      userEditClick(row) {
        this.userEditForm.userId = row.userId
        this.userEditForm.userCardId = row.userCardId
        this.editUserDialog = true
      },
      editUserDialogClosed() {},
      async editUser() {
        const res = await this.$apiUtil.postByJson('user/editUser', this.userEditForm)
        console.log(res)
        if (res.code !== '200') {
          return this.$message.error(res.msg)
        }
        this.editUserDialog = false
        this.getUserList()
      },
      async roleClick(row) {
        this.userRoleDialog = true
        const res = await this.$apiUtil.get('role/list', {})
        console.log(res)
        if (res.code !== '200') {
          return this.$message.error(res.msg)
        }
        this.roleOptions = res.data
        this.userId = row.userId
        this.roleSelect = row.roleName
      },
      async editUserRole() {
        const res = await this.$apiUtil.postByForm('user/editUserRole', {
          userId: this.userId,
          roleName: this.roleSelect
        })
        console.log(res)
        if (res.code !== '200') {
          return this.$message.error(res.msg)
        }
        this.$message.success('编辑用户角色成功')
        this.userRoleDialog = false
        this.getUserList()
      },
      async menuClick(row) {
        this.menuPowerDialog = true
        const res = await this.$apiUtil.get('menu/userMenuPowerList', {
          userId: row.userId
        })
        console.log(res)
        if (res.code !== '200') {
          return this.$message.error(res.msg)
        }
        this.userMenuList = res.data.children
        this.userId = row.userId
        const keys = []
        for (let i = 0, len = this.userMenuList.length; i < len; i++) {
          if (this.userMenuList[i].children !== undefined) {
            for (let j = 0, len = this.userMenuList[i].children.length; j < len; j++) {
              if (this.userMenuList[i].children[j].isEnable) {
                keys.push(this.userMenuList[i].children[j].menuRoot)
              }
            }
          } else if (this.userMenuList[i].isEnable) {
            keys.push(this.userMenuList[i].menuRoot)
          }
        }
        this.$refs.userMenuListTreeRef.setCheckedKeys(keys)
      },
      async editUserPower() {
        const userMenuPowers = this.$refs.userMenuListTreeRef.getCheckedKeys().concat(this.$refs.userMenuListTreeRef.getHalfCheckedKeys())
        const res = await this.$apiUtil.postByJson('user/userMenuPowerEdit', {
          userId: this.userId,
          userMenuPowers: userMenuPowers
        })
        console.log(res)
        if (res.code !== '200') {
          return this.$message.error(res.msg)
        }
        this.$message.success('编辑菜单权限成功')
        this.menuPowerDialog = false
      },
      async powerClick(row) {
        this.userPowerDialog = true
        const res = await this.$apiUtil.postByForm('power/userPowerList', {
          userId: row.userId
        })
        console.log(res)
        if (res.code !== '200') {
          return this.$message.error(res.msg)
        }
        this.userPowerList = res.data
        this.userId = row.userId
      },
      async userPowerStatusChange(row) {
        const res = await this.$apiUtil.postByForm('user/userPowerEdit', {
          userId: this.userId,
          powerName: row.powerName
        })
        console.log(res)
        if (res.code !== '200') {
          row.isEnable = !row.isEnable
          return this.$message.error(res.msg)
        }
        this.$message.success('修改角色权限成功')
      },
      deleteClick(userId, userName) {
        this.$alert('确定删除用户:' + userName + ' ! ! !', '提示', {
          confirmButtonText: '确定',
          center: true,
          callback: async action => {
            if (action === 'confirm') {
              const res = await this.$apiUtil.postByForm('user/delete', {
                userId: userId
              })
              console.log(res)
              if (res.code !== '200') {
                return this.$message.error(res.msg)
              }
              this.$message.success('删除用户成功')
              this.getUserList()
            }
          }
        })
      }
    },
    created() {
      this.getUserList()
    }
  }
</script>

<style lang="less" scoped>
</style>
